/*
 * @author: huangww
 * @Date: 2021-02-24 16:04:59
 * @LastEditTime: 2021-02-26 10:16:44
 * @FilePath: \fmgr\src\core\net\Socket.ts
 */
namespace core {
  /**webSocket封装，包含心跳检测 */
  export class Socket {
    public webSocket: egret.WebSocket;
    //连接地址
    public socketUrl: string;
    private counter: number = 0;
    //断线重连定时器
    public timer: egret.Timer;
    constructor() {
      this.webSocket = new egret.WebSocket();
    }

    connect(url: string) {
      this.webSocket.connectByUrl(url);
      //添加接收消息监听
      this.webSocket.addEventListener(egret.ProgressEvent.SOCKET_DATA, (e: egret.Event) => {
        const msg = this.webSocket.readUTF();

        if (msg == null || msg == undefined || msg == "") {
          console.log("空报文!");
          return;
        }
        if (msg.split('{"action"').length > 2) {
          msg.split('{"action"').forEach((mitem, idf) => {
            if (mitem != "") {
              this.receiveMessage(JSON.parse('{"action"' + mitem));
            }
          });
          return;
        }
        this.receiveMessage(JSON.parse(msg));
      }, this);

      //创建连接监听
      this.webSocket.addEventListener(egret.Event.CONNECT, (e: egret.Event) => {
        console.log("连接成功!");
        this.createTimer();
      }, this);

      //连接断开监听
      this.webSocket.addEventListener(egret.Event.CLOSE, (e: egret.Event) => {
        console.log("连接失败!");
      }, this);

      this.webSocket.addEventListener(egret.IOErrorEvent.IO_ERROR, (e) => {
        this.reconnect();
      }, this);
    }

    //将消息交给各个handler处理
    public receiveMessage(msg: Msg) {
      DataMgr.getInstance().setData(msg);
    }

    reconnect() {
      if (!this.webSocket.connected) {
        this.webSocket.connectByUrl(this.socketUrl);
      }
    }

    createTimer() {
      this.counter = 0;
      if (this.timer) {
        if (this.timer.running) {
          this.timer.stop();
        }
      }
      this.timer = new egret.Timer(5000);
      this.timer.addEventListener(egret.TimerEvent.TIMER, this.timerFunc, this);
      this.timer.start();
    }

    //达到定时器延时触发
    private timerFunc(event: egret.TimerEvent) {
      if (!this.webSocket.connected) {
        if (this.counter < 12) {
          this.counter++;
          if (this.counter % 2 == 0) { }
        } else { }
      } else { }
    }

    send(msg: Msg) {
      if (this.webSocket.connected) {
        this.webSocket.writeUTF(JSON.stringify(msg));
      }
    }




  }
}